package com.jeesite.modules.student.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 下载文件工具包Util，用于下载学生表模板
 * @author 梁师豪LXH
 * @version 2021-07-17
 */
public class DownloadFileUtil {

    /**
     * 将文件下载到客户端
     *
     * @param filePath
     * @param fileName
     * @param response
     * @param isOnLine
     *            是否在线打开
     * @throws Exception
     */
    public static void download(String filePath, String fileName, HttpServletRequest request,
                                HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        /*
         * if (!f.exists()) { response.sendError(404, "File not found!");
         * return; }
         */
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        // 用于下载文件excel操作时
        // 非常重要，清除首部的空白行
        response.reset();
        // 解决文件名中文乱码问题
        String fileNameDisplay = URLEncoder.encode(fileName, "UTF-8");
        // 针对火狐浏览器需要特殊处理
        if ("FF".equals(getBrowser(request))) {
            fileNameDisplay = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }
        // 在线打开方式
        if (isOnLine) {
            URL url = new URL(filePath);
            response.setContentType(url.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + fileNameDisplay);
        }
        // 纯下载方式
        else {
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileNameDisplay);
        }

        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        out.flush();
        br.close();
        out.close();
    }

    /**
     * 判断客户端浏览器类型
     *
     * @param request
     * @return
     */
    private static String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent != null) {

            if (UserAgent.indexOf("msie") >= 0){
                return "IE";
            }

            if (UserAgent.indexOf("firefox") >= 0){
                return "FF";
            }

            if (UserAgent.indexOf("safari") >= 0){
                return "SF";
            }

        }
        return null;
    }

}
